'''
Created on Jun 8, 2013

@author: Cihat Basol
'''

import logging
import time

import rpyc
from rpyc.utils.server import ThreadedServer
from pymongo.mongo_client import MongoClient

from dexen.common import remoting, constants, utils
from dexen.node import env_mgr
from dexen.node.worker import core


#===============================================================================
# Globals
#===============================================================================
_server_addr = None
_worker_name = ""
_job_name = None
_core = None

#===============================================================================
# 
#===============================================================================
class WorkerEndPoint(remoting.BaseEndPoint):
    def on_connect(self):
        pass

    def on_disconnect(self):
        pass

    def get_associated_job(self):
        return _job_name

    def execute(self, execution):
        execution = rpyc.classic.obtain(execution)
        _core.execute(execution)

    def get_execution_result(self):
        return _core.get_execution_result()

#===============================================================================
# 
#===============================================================================
def init_dir():
    worker_dir = env_mgr.get_worker_dir(_worker_name, create=True)
    utils.del_tree(worker_dir)


def start(server_addr, worker_name, job_name=None):
    global _server_addr, _worker_name, _job_name, _core
    _server_addr = server_addr
    _worker_name = worker_name
    _job_name = job_name

    init_dir()

    db_client = MongoClient(server_addr.ip, constants.MONGOD_PORT)
    _core = core.WorkerCore(_worker_name, db_client, _job_name)
    _core.start()

    worker_endpoint = ThreadedServer(WorkerEndPoint,
                                     protocol_config=remoting.DEFAULT_CONFIG,
                                     logger=logging.getLogger(__name__+"."+
                                                              _worker_name))
    server_conn = remoting.connect(server_addr)
    my_addr = remoting.EndPointAddress(remoting.get_my_ip(), worker_endpoint.port)
    _node_name = server_conn.root.register_worker(my_addr, _worker_name)
    time.sleep(5)
    server_conn.close()
    worker_endpoint.start()

